package com.googlecode.contests_repo.servlets;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.contests_repo.core.config.ConfigurationManager;
import com.oreilly.servlet.MultipartRequest;

/**
 * A servlet for uploading files in the repository.
 * 
 * @author deni
 */
@WebServlet("/upload_file")
public class UploadFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String repoRoot = ConfigurationManager.getInstance().getRepoRoot();

		String encodedLocation = "";
		boolean success = true;
		try {
			MultipartRequest mpRequest = new MultipartRequest(request,
					repoRoot, Integer.MAX_VALUE);

			encodedLocation = mpRequest.getParameter("location");
			// String location = URLDecoder.decode(encodedLocation, "UTF-8");
			String location = encodedLocation;
			String absoluteLocation = repoRoot + File.separator + location;
			
			File file = mpRequest.getFile("file");
			if (file != null) {
				success = file.renameTo(new File(absoluteLocation
						+ File.separator + file.getName()));
			}
			assert success;

		} catch (IOException e) {
			e.printStackTrace();
			success = false;
		}
		// response.sendRedirect("view_folder.jsp?path=" + encodedLocation +
		// "&fileUploadSuccessful=" + success);
		response.sendRedirect("resource.jsp?path=" + encodedLocation
				+ "&edit=1");

	}

}
